package sketch.generator;

/**
 * Exhaustively iterates its children nodes
 * */
public class CombinatoricLink extends BinaryLink {
	
	//the initial state
	private boolean isReset = true;

	public CombinatoricLink() {
		super();
	}
	
	public CombinatoricLink(IIterationLink left, IIterationLink right) {
		super(left, right);
	}
	
	public CombinatoricLink(IGenerator<?> leftGen, IGenerator<?> rightGen) {
		super(leftGen, rightGen);
	}
	
	@Override
	public void reset() {
		super.reset();
		isReset = true;
	}
	
	@Override
	public boolean hasNext() {
		return getLeft().hasNext() || getRight().hasNext();
	}

	@Override
	public void next() {
		IIterationLink left = getLeft();
		IIterationLink right = getRight();
		/**
		 * If left = [1, 2]
		 *     right = [3, 4]
		 * The next() will produce the following pairs:
		 *     [1, 3] [1, 4] [2, 3] [2, 4]
		 * **/
		if(!right.hasNext()) {
			right.reset();
			if(!left.hasNext()) {
				throw new IterationException("There is no more item to" +
						" iterate in CombinatoricLink.");
			}
			left.next();
		}
		right.next();
		if(isReset) {
			left.next();
			isReset = false;
		}
	}

	@Override
	public BinaryLink createNewInstance(IIterationLink left,
			IIterationLink right) {
		return new CombinatoricLink(left, right);
	}

}
